package com.github.shiqiyue.myadmin.controller.system.user;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.shiqiyue.myadmin.config.security.anontation.Authority;
import com.github.shiqiyue.myadmin.config.security.anontation.AuthorityConfig;
import com.github.shiqiyue.myadmin.config.security.common.AuthorityCommon;
import com.github.shiqiyue.myadmin.config.syslog.anontation.SysLog;
import com.github.shiqiyue.myadmin.controller.base.AdminBaseController;
import com.github.shiqiyue.myadmin.entity.common.Editable;
import com.github.shiqiyue.myadmin.entity.system.Role;
import com.github.shiqiyue.myadmin.entity.system.User;
import com.github.shiqiyue.myadmin.service.system.role.RoleService;
import com.github.shiqiyue.myadmin.service.system.user.UserService;
import com.github.shiqiyue.myadmin.util.json.JsonUtils;
import com.github.shiqiyue.myadmin.vo.rep.base.RepBase;
import com.github.shiqiyue.myadmin.vo.rep.base.RepPage;
import com.github.shiqiyue.myadmin.vo.req.page.ReqPageVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/**
 * 会员管理
 *
 * @author wwy
 *
 * @version
 */
@Controller
@AuthorityConfig(prefix = "/admin/user/list")
@RequestMapping(value = "admin/user")
public class UserController extends AdminBaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;

    @Autowired
    @Qualifier("adminPasswordEncoder")
    private PasswordEncoder passwordEncoder;

	/**
	 * 去列表页面
     *
	 */
	@Authority(name = AuthorityCommon.LIST)
	@GetMapping(value = "/list")
    public String toList(Model model) {

        return "pages/user/user-list";
    }

	/**
	 * 列表数据
	 */
	@SysLog("查询用户列表数据")
	@Authority(name = AuthorityCommon.LIST)
	@PostMapping(value = "/list")
	@ResponseBody
    public RepBase list(ReqPageVO pageVO, @RequestParam Map<String, Object> map) {
        RepBase rep = new RepBase<>();
		processParams(map);
		Page<User> page = processPage(pageVO);
		page = userService.list(page, map);
        RepPage repPage = new RepPage(page.getRecords(), page.getTotal());
        return rep.setCommonSuccess().setData(repPage);
	}

	/**
	 * 去新增页面
	 */
	@Authority(name = AuthorityCommon.ADD)
	@GetMapping(value = "/add")
    public String goAdd(Model model) {
        List<Role> roleList = roleService.selectList(new EntityWrapper<>());
        model.addAttribute("json", JsonUtils.beanToString(roleList));
        model.addAttribute("entity", new User());
        return "pages/user/user-edit";
    }



	/**
	 * 保存
	 */
	@SysLog("添加用户数据")
	@Authority(name = AuthorityCommon.ADD)
	@PostMapping(value = "/add")
	@ResponseBody
    public RepBase save(User entity) {
        RepBase rep = new RepBase();
        boolean userNameExist = userService.selectCount(new EntityWrapper<User>().eq("username", entity.getUsername())) > 0;
        if (userNameExist) {
            return rep.setCommonFail().setMes("用户名已存在");
        }
        if (StringUtils.isBlank(entity.getPassword())) {
            return rep.setCommonFail().setMes("请输入密码");
        }
        entity.setPassword(passwordEncoder.encode(entity.getPassword()));
		entity.setDel(false);
		entity.setEnable(true);
		userService.insert(entity);
        return rep.setCommonSuccess();
	}

	/**
	 * 去修改页面
	 */
	@Authority(name = AuthorityCommon.EDIT)
	@GetMapping(value = "/edit")
	public String goEdit(String id, Model model) {
		List<Role> roleList = roleService.selectList(new EntityWrapper<>());
		model.addAttribute("json", JsonUtils.beanToString(roleList));
		model.addAttribute("entity", userService.selectById(id));
		return "pages/user/user-edit";
	}

	/**
	 * 修改
	 */
	@SysLog("修改用户数据")
	@Authority(name = AuthorityCommon.EDIT)
	@PostMapping(value = "/edit")
	@ResponseBody
    public RepBase edit(User entity) {
        RepBase rep = new RepBase<>();
		User user = userService.selectById(entity.getId());
		if (user.getEditable().equals(Editable.NO)) {
            return rep.setCommonFail().setMes("用户不可编辑");
        }
        boolean userNameExist = userService.selectCount(new EntityWrapper<User>().eq("username", entity.getUsername()).ne("id", entity.getId())) > 0;
        if (userNameExist) {
            return rep.setCommonFail().setMes("用户名已存在");
        }
		if (StringUtils.isNotBlank(entity.getPassword())) {
            user.setPassword(passwordEncoder.encode(entity.getPassword()));
		}
		user.setUsername(entity.getUsername());
		user.setRoleId(entity.getRoleId());
		user.setNickname(entity.getNickname());
		user.setPhone(entity.getPhone());
		user.setEmail(entity.getEmail());
		user.setPhotoUrl(entity.getPhotoUrl());
		user.setRemarks(entity.getRemarks());
		user.setEnable(entity.getEnable());
		userService.updateById(user);
        return rep.setCommonSuccess();
	}

	/**
	 * 删除
	 */
	@SysLog("删除用户数据")
	@Authority(name = AuthorityCommon.DELETE)
    @PostMapping(value = "/del")
	@ResponseBody
    public RepBase delete(String id) {
		userService.delete(new EntityWrapper<User>().eq("id", id).eq("editable", Editable.YES));
        return RepBase.newIntance().setCommonSuccess();
	}

    /**
	 * 批量删除
	 */
	@SysLog("批量删除用户数据")
	@Authority(name = AuthorityCommon.DELETE)
    @PostMapping(value = "/batch/del")
	@ResponseBody
    public RepBase deleteAll(@RequestParam("ids[]") List<String> ids) {
        RepBase rep = new RepBase<>();
        if (CollectionUtils.isNotEmpty(ids)) {
			userService.delete(new EntityWrapper<User>().in("id", ids).eq("editable", Editable.YES));
		}
        return rep.setCommonSuccess();
	}


}
